var express = require('express');
var router = express.Router();
const Article = require('./models');

/* GET home page. */
router.get('/', async function(req, res, next) {
  const list = await Article.find();
  res.locals.list = list;
  res.render('index');
  // res.render('index', { title: 'Express' });
});



// create Article
router.post('/create', async function(req, res){
  const {title,body} = req.body;
  const article = new Article({
    title,body,
    createTime:new Date(),
    updateTime:new Date()
  });
  await article.save();
  res.redirect("/");
});
router.get('/create', function(req, res){
  res.render("create")
});

// delete Article
router.get('/delete/:id',async function(req, res){
  await Article.remove({_id:req.params.id});
  res.redirect('/');
});

// update Article
router.post('/update/:id',async function(req, res){
  const id = req.params.id;
  const {title,body} = req.body;
  const article = await Article.findById(id);
  if(article){
    article.title = title;
    article.body = body;
    article.updateTime = new Date();
    await article.save();
  }
  res.redirect('/');
});
router.get('/update/:id',async function(req, res){
  const id = req.params.id;
  const article = await Article.findById(id);
  res.locals.id = id;
  res.locals.article = article;
  res.render('update');
});

module.exports = router;
